/*
 * config.cpp
 *
 *  Created on: 28-Apr-2009
 *      Author: catchthealien
 */
#include <cssysdef.h>

#include <stdio.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <sys/stat.h>
#include <stdlib.h>

#include "cs.h"
#include "parser.h"

#include "config.h"

namespace cta {

config::config() {
}

bool config::ReadConfig()
{
	// Variables for Screen Init
	XResolution = 0;
	YResolution = 0;
	BPP = 0;
	// Variables for Config File (/home/user/.cta/config.xml)
	std::stringstream configfile;
#ifdef WIN32

#else
	configfile << getenv("HOME") << "/.cta/";
#endif
	ConfigPath = configfile.str();
	configfile << "config.xml";
	ConfigFile = configfile.str();
	StandardConfigFile = "/data/config/config.xml";
	struct stat fileStatus;
	int iretStat = stat(ConfigFile.c_str(), &fileStatus);
	if(iretStat!=0)
		return ReadConfig(StandardConfigFile);
	else
		return ReadConfig(ConfigFile);
}

bool config::ReadConfig(std::string &FileName)
{
	parser xmlParser;
	csRef<iVFS> fs = cs::c().fs;
	if (!fs)
	{
		std::cout << "Failed to locate virtual file system!" << std::endl;
	}
	csRef<iDataBuffer> data = fs->ReadFile(FileName.c_str());
	if (!data.IsValid())
	{
		return false;
	}else{

		std::string datastring = data->GetData();
		XResolution = xmlParser.getIntegerFromString(datastring, "ScreenResolution", "Width");
		YResolution = xmlParser.getIntegerFromString(datastring, "ScreenResolution", "Height");
		BPP = xmlParser.getIntegerFromString(datastring, "ScreenResolution", "BPP");
#ifdef DEBUG
		std::cout << "Config read" << std::endl;
#endif
		return true;
	}
}

bool config::WriteConfig()
{
	return WriteConfig(ConfigFile);
}

bool config::WriteConfig(std::string &FileName)
{

	//TODO: make dir

#ifdef DEBUG
	std::cout << "config file: " << FileName.c_str() << std::endl;
#endif

	std::stringstream xmlstring;
	// write xmlfile into stringstream
	xmlstring << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" << std::endl;
	xmlstring << "<cta>" << std::endl;
	xmlstring << "\t<ScreenResolution" << std::endl;
	xmlstring << "\t\tWidth=\"" << XResolution << "\"" << std::endl;
	xmlstring << "\t\tHeight=\"" << YResolution << "\"" << std::endl;
	xmlstring << "\t\tBPP=\"" << BPP << "\"" << std::endl;
	xmlstring << "\t\t>" << std::endl;
	xmlstring << "\t</ScreenResolution>" << std::endl;
	xmlstring << "</cta>";
#ifdef DEBUG
	std::cout<< xmlstring.str().c_str() << std::endl;
#endif
	csRef<iVFS> fs = cs::c().fs;
	csRef<iDataBuffer> write;
	fs->WriteFile(FileName.c_str(), xmlstring.str().c_str(), xmlstring.str().size());

	/*std::ofstream xmlfile;
	xmlfile.open(FileName.c_str());
	if(!xmlfile.is_open())
	{
		std::stringstream task;
		task << "mkdir " << ConfigPath;
		system(task.str().c_str());
		xmlfile.open(FileName.c_str());
	}
	xmlfile << xmlstring.str().c_str();
	xmlfile.close();
*/
#ifdef DEBUG
	std::cout<< xmlstring.str().c_str() << std::endl;
#endif


	return true;
}

config::~config() {
	// TODO Auto-generated destructor stub
}

}
